const dgram = require('dgram');
const sockets = [];
var name;
const server = dgram.createSocket('udp4');

var now_num=0;
server.on('message', (message, remote) => {
    const addr = `${remote.address}:${remote.port}`;
    console.log(`Received message from ${addr}: ${message}`);
    // 处理新的连接请求
    if (!sockets.some(s => s.address === remote.address && s.port === remote.port)) { //防止同接口多次接入造成重复发包
      sockets.push(remote);
    }
    
    

    // 解析请求
    const parts = message.toString().split(' ');
    const command = parts[0].toLowerCase();

    // 将消息发送到其他客户端
    if (command == 'name') {
        // 设置客户端名称
        name = parts[1];
        console.log(`客户端已设置名称为：${name}`);
        now_num ++;
        const addname = `${name}已加入群聊`;
        sockets.forEach((s) => {
            if (s.address !== remote.address || s.port !== remote.port) {
              server.send(addname, s.port, s.address);
              console.log(`已发送 ${addname}`);
            }
            updateClientCount(s);
        });
        
    }
    
    else if (command === 'exit') {
      // 客户端退出
      const name = parts[1];
      const message = `用户 ${name} 已退出聊天室`;
      now_num--;
      
      sockets.forEach((s) => {
        updateClientCount(s);
        server.send(message, s.port, s.address);
        console.log(`已发送 ${message}`);
      });
    }
    else{
        sockets.forEach((s) => {
            if (s.address !== remote.address || s.port !== remote.port) {
              server.send(message, s.port, s.address);
              console.log(`已发送 ${message}`);
            }
        });
    }
});

server.on('listening', () => {
    const address = server.address();
    sockets.forEach((s) => {
      
    updateClientCount(s)        
      
  });
    console.log(`UDP Server listening on ${address.address}:${address.port}`);
});

// server.on('close', () => {
//   const index = sockets.indexOf(remote);
//   if (index !== -1) {
//     if (name) {
//       const message = `用户 ${rote.name} 已退出聊天室`;
//       sockets.forEach((s) => {
//         if (s.address !== remote.address || s.port !== remote.port) {
//           server.send(message, s.port, s.address);
//           console.log(`已发送 ${message}`);
//           updateClientCount(s);
//         }
//       });
//     }
//     sockets.splice(index, 1);
//   }
// });

// server.on('error', (err) => {
//   console.error(`Error occurred: ${err}`);
// });

server.bind(3000);

function updateClientCount(remote) {
    const numClients = sockets.length;
    const controlMessage = `now_member ${now_num}`;
    console.log(controlMessage);
    server.send(controlMessage, remote.port, remote.address);
}